package com.example.sharingjdbcdemo.sharing;

import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingValue;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName ComplexShardingAlgorithm
 * @Description TODO
 * @Author 郭敖
 * @Date 2023年11月07日 21:42
 * @Version 1.0
 */
public class ComplexShardingAlgorithm implements ComplexKeysShardingAlgorithm {
    @Override
    public Collection<String> doSharding(Collection collection, ComplexKeysShardingValue complexKeysShardingValue) {
        Map columnNameAndShardingValuesMap = complexKeysShardingValue.getColumnNameAndShardingValuesMap();
        List<Long> idList = (List<Long>) columnNameAndShardingValuesMap.get("id");
        List<LocalDateTime> timeList = (List<LocalDateTime>) columnNameAndShardingValuesMap.get("create_time");
        Map rangeValuesMap = complexKeysShardingValue.getColumnNameAndRangeValuesMap();
        List<String> tableName = new ArrayList<>();
        StringBuilder builder = new StringBuilder();
        if(idList != null && timeList != null){
            builder.append(complexKeysShardingValue.getLogicTableName());
            builder.append("_");
            for (LocalDateTime time : timeList){
                builder.append(time.getMonth().getValue());
                for (Long id: idList){
                    builder.append("_");
                    builder.append(id%3);
                    tableName.add(builder.toString());
                }
                builder = new StringBuilder();
            }
            return tableName;
        }
        return (Collection<String>) collection;
    }


    @Override
    public String getType() {
        return null;
    }

    @Override
    public Properties getProps() {
        return null;
    }

    @Override
    public void init(Properties properties) {

    }
}
